<script setup lang="ts">
import router from '@/router'
import {
  getConsultOrderPre,
  getPatientDetail,
  payMoneyOrder,
  getConsultOrderPayUrl
} from '@/services'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData, PayMoneyType } from '@/types/consult'
import type { PatientType } from '@/types/user'
import { showConfirmDialog, showDialog, showLoadingToast, showToast } from 'vant'
import { ref } from 'vue'
import { onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'

onMounted(() => {
  if (!consultStore.consult.type) {
    // 只有一个确认按钮
    showDialog({
      title: '温馨提示',
      message: '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付'
    }).then(() => {
      // 跳转到首页并且不会请求下面的接口
      router.push('/')

      // 不请求下面的接口
    })
    return
  }
  getPay()
  getPatient()
})

const consultStore = useConsultStore()
const payInfo = ref({} as ConsultOrderPreData)
const getPay = async () => {
  const res = await getConsultOrderPre({
    type: consultStore.consult.type,
    illnessType: consultStore.consult.illnessType
  })
  payInfo.value = res.data
}

const patientInfo = ref({} as PatientType)
const getPatient = async () => {
  const res = await getPatientDetail(consultStore.consult.patientId as string)
  console.log(res)
  patientInfo.value = res.data
}

// 支付
const agree = ref(false)
const orderId = ref('')
const loading = ref(false)
const toPayMoney = async () => {
  if (!agree.value) return showToast('请勾选我已同意')
  try {
    loading.value = true
    const res = await payMoneyOrder(consultStore.consult)
    orderId.value = res.data.id
    // 数据已经使用完成, 所以我们要清除全局数据
    consultStore.clear()
    // 打开抽屉
    show.value = true
  } finally {
    loading.value = false
  }
}

// 抽屉操作
const show = ref(false)

/**
 * 放弃支付的几种方式
 *    1. 点击黑色区域, 点击仍要关闭,就放弃支付,关闭抽屉, 跳转到问诊订单页
 *    2. 如果已经生成了订单了, 单击返回按钮时, 不可以回退
 *    3. 刷新页面时: 判断问诊记录是否存在,
 */

//抽屉的回调函数
const beforeClose = async () => {
  try {
    // 点击继续支付
    await showConfirmDialog({
      title: '关闭支付',
      message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
      cancelButtonText: '仍要关闭',
      confirmButtonText: '继续支付'
    })

    // 如果使用return false那么就不关闭按钮
    return false
  } catch (error) {
    // 点击仍要关闭
    // 清空订单
    orderId.value = ''
    // 跳转到问诊订单页面
    router.push('/user/consult')
    // 关闭抽屉,
    return true
  }
}

// 如果订单生成点击回退按钮 不可以回退
// 这个路由 其实已经跳走了, 但是又跳回来了, 所以相当于没有跳转
onBeforeRouteLeave(() => {
  if (orderId.value) return false
})
</script>

<template>
  <div class="consult-pay-page">
    <cp-nav-bar title="支付" />
    <!-- 预支付信息 -->
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <!-- 患者信息 -->
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patientInfo.name} | ${patientInfo.genderValue} | ${patientInfo.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="consultStore.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <!-- 底部操作栏 -->
    <!-- 防止用户持续点击 使用loading 进行优化 loading -->
    <van-submit-bar
      :loading="loading"
      button-type="primary"
      :price="payInfo.payment * 100"
      button-text="立即支付"
      text-align="left"
      @click="toPayMoney"
    />
    <!-- 抽屉 -->
    <cp-pay-sheet
      v-model:show="show"
      :orderId="orderId"
      :actualPayment="payInfo.actualPayment"
      :beforeClose="beforeClose"
      payCallback="/room"
    ></cp-pay-sheet>
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
</style>
